package processor;

import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.message.BasicNameValuePair;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.utils.HttpConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangcheng on 2017/4/21 0021.
 */
public class CasePageProcessor implements PageProcessor {
    private Site site = Site.me()
            .setRetryTimes(3)
            .setHttpProxy(new HttpHost("10.101.1.6",80))
            ;

    public void process(Page page) {
        System.out.println(page.getHtml());
        List<String> dates = page.getHtml().xpath("//div[@class='pasgersound-dl']/dl/dd[1]/p[3]/text()").all();
        for(String str:dates)
            System.out.println(str);
    }

    public Site getSite() {
        return this.site;
    }

    public static void main(String[] args) {
        //设置POST请求
        Request request = new Request("https://www.capse.net/sound/comments?p=2");
        //只有POST请求才可以添加附加参数
        request.setMethod(HttpConstant.Method.POST);
        //设置POST参数
        List<NameValuePair> nvs = new ArrayList<NameValuePair>();
        nvs.add(new BasicNameValuePair("page", "1"));
        nvs.add(new BasicNameValuePair("limit", "2"));
        nvs.add(new BasicNameValuePair("ajaxUrl", "https://www.capse.net/sound/comments"));
        //转换为键值对数组
        NameValuePair[] values = nvs.toArray(new NameValuePair[]{});
        //将键值对数组添加到map中
        Map<String, Object> params = new HashMap<String, Object>();
        //key必须是：nameValuePair
        params.put("nameValuePair", values);
        //设置request参数
        request.setExtras(params);
        Spider.create(new CasePageProcessor()).addRequest(request).run();
    }
}
